export const DB = "map";

//监听数据库是否开启
export const isOpen = () => {
  return plus.sqlite.isOpenDatabase({
    name: DB,
    path: `_doc/${DB}.db`,
  });
};

export const openDb = () => {
  const name = DB;
  if (isOpen()) return;

  //如果数据库存在则打开，不存在则创建。
  return new Promise((resolve, reject) => {
    plus.sqlite.openDatabase({
      name: name, //数据库名称
      path: `_doc/${name}.db`, //数据库地址
      success(e: any) {
        resolve(e);
      },
      fail(e: any) {
        reject(e);
      },
    });
  });
};

// 查询表是否存在
export const hasTable = (tabName: string) => {
  const name = DB;
  return new Promise((resolve, reject) => {
    plus.sqlite.selectSql({
      name: name,
      sql: `select name FROM sqlite_master where type='table' and name='${tabName}'`,
      success(e: any) {
        resolve(e.length > 0);
      },
      fail(e: any) {
        console.log(e);
        reject(e);
      },
    });
  });
};

export const delTable = (tableName: string) => {
  return new Promise((resolve, reject) => {
    plus.sqlite.selectSql({
      name: DB,
      sql: `DROP TABLE IF EXISTS ${tableName};`,
      success(e: any) {
        resolve(e);
      },
      fail(e: any) {
        console.log(e);
        reject(e);
      },
    });
  });
};

export const createLayerTable = () => {
  return new Promise((resolve, reject) => {
    console.log("初始化数据表layer");
    plus.sqlite.executeSql({
      name: DB,
      sql: `create table if not exists layer (
    "id" INTEGER PRIMARY KEY AUTOINCREMENT,
    "name" TEXT NOT NULL UNIQUE,
    "type" TEXT, 
    "parentId" INTEGER, 
    "custom" INTEGER,
    "remark" TEXT,
    "weight" INTEGER)`,
      success(e: any) {
        console.log(e);
        resolve(e);
      },
      fail(e: any) {
        console.log(e);
        reject(e);
      },
    });
  });
};

export const createDataTable = () => {
  return new Promise((resolve, reject) => {
    console.log("初始化数据表data");
    plus.sqlite.executeSql({
      name: DB,
      sql: `create table if not exists data (
    "id" INTEGER PRIMARY KEY AUTOINCREMENT,
    "name" TEXT,"type" TEXT,
    "layerId" TEXT NOT NULL,
    "area" FLOAT,
    "info" TEXT,
    "remark" TEXT,
    "nature" TEXT,
    "geometry" TEXT)`,
      success(e: any) {
        resolve(e);
      },
      fail(e: any) {
        console.log(e);
        reject(e);
      },
    });
  });
};
